//
//  CustomURLController.m
//  IvideoApiClient
//
//  Created by fudo on 16/11/15.
//  Copyright © 2016年 sumavision. All rights reserved.
//

#import "CustomURLController.h"
#import <OMCService/OMCService.h>


@interface CustomURLController ()

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIButton *sendBtn;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UITextView *responseView;
@property (nonatomic, strong) UISegmentedControl *segment;

@end

static NSString *responseText;
static NSString *errorText;

@implementation CustomURLController

- (instancetype)init {
    if (self = [super init]) {
        _segment = [[UISegmentedControl alloc] initWithItems:@[@"Request", @"Respose", @"error"]];
        _segment.frame = CGRectMake(20, 84, [UIScreen mainScreen].bounds.size.width-40, 29);
        _segment.selectedSegmentIndex = 0;
        [_segment addTarget:self action:@selector(segmentChanged) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_segment];
        
        _label = [[UILabel alloc] initWithFrame:CGRectMake(20, 123, [UIScreen mainScreen].bounds.size.width-40, 29)];
        _label.text = @"请输入URL:";
        [self.view addSubview:_label];
        
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 152, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-410)];
        _textView.delegate = self;
        _textView.returnKeyType = UIReturnKeyDone;
        _textView.font = [UIFont systemFontOfSize:15];
        [self.view addSubview:_textView];
        
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        
        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sendBtn.frame = CGRectMake(20, CGRectGetMaxY(_textView.frame)+20, width-40, 44);
        [_sendBtn setTitle:@"Send" forState:UIControlStateNormal];
        _sendBtn.backgroundColor = [UIColor colorWithRed:0.0 green:103.0/255 blue:255.0/255 alpha:1];
        _sendBtn.layer.cornerRadius = 5.0;
        [_sendBtn addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_sendBtn];
        
        _responseView = [[UITextView alloc] initWithFrame:CGRectMake(0, 133, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-221)];
        _responseView.editable = NO;
        _responseView.hidden = YES;
        [self.view addSubview:_responseView];
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:235.0f/255 green:235.0f/255 blue:241.0f/255 alpha:1];
    
    UIBarButtonItem *sendBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"配置Portal地址" style:UIBarButtonItemStylePlain target:self action:@selector(configBaseURL)];
    self.navigationItem.rightBarButtonItem = sendBarBtn;
    
   
}

- (void)send {
    NSURL *requestURL = [NSURL URLWithString:self.textView.text];
    NSURLSessionDataTask *task = [[OMCApiClient sharedApiClient] request_JsonDataWith_URL:requestURL
                                                       withMethodType:Get
                                                          bodyJsonStr:nil
                                                              success:^(NSURLSessionDataTask *sessionTask, NSDictionary *responseDic) {
                                                                  dispatch_async(dispatch_get_main_queue(), ^{
                                                                      if ([responseDic[@"status"] isEqualToString:@"0"]) {
                                                                          errorText = @"";
                                                                          responseText = [sessionTask getIvideoApiResponseDataString];
                                                                          self.segment.selectedSegmentIndex = 1;
                                                                      } else {
                                                                          responseText = @"";
                                                                          // 调用底层的验证响应数据的方法
                                                                          NSError *error = [[OMCApiBaseManager sharedManager] validateResponseObj:responseDic];
                                                                          errorText = [NSString stringWithFormat:@"%@", error];
                                                                          self.segment.selectedSegmentIndex = 2;
                                                                      }
                                                                      [self.segment sendActionsForControlEvents:UIControlEventValueChanged];
                                                                  });
                                                              }
                                                              failure:^(NSURLSessionDataTask *sessionTask, NSError *error) {
                                                                  dispatch_async(dispatch_get_main_queue(), ^{
                                                                      responseText = @"";
                                                                      errorText = [NSString stringWithFormat:@"%@", error];
                                                                      self.segment.selectedSegmentIndex = 2;
                                                                      [self.segment sendActionsForControlEvents:UIControlEventValueChanged];
                                                                  });
                                                              }];
    NSLog(@"%@", task);
}

- (void)configBaseURL
{
    UIAlertView *customAlertView = [[UIAlertView alloc] initWithTitle:@"请输入Portal地址：" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *tf = [customAlertView textFieldAtIndex:0];
    tf.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"baseURL"];
    [customAlertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == alertView.firstOtherButtonIndex)
    {
        UITextField *tf = [alertView textFieldAtIndex:0];
        NSString *baseURL = tf.text;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:baseURL forKey:@"baseURL"];
    }
}

- (void)segmentChanged {
    switch (self.segment.selectedSegmentIndex) {
        case 0:
            self.label.hidden = NO;
            self.textView.hidden = NO;
            self.responseView.hidden = YES;
            break;
        case 1:
            self.responseView.text = responseText;
            self.label.hidden = YES;
            self.textView.hidden = YES;
            self.responseView.hidden = NO;
            [self.textView resignFirstResponder];
            break;
        case 2:
            self.responseView.text = errorText;
            self.label.hidden = YES;
            self.textView.hidden = YES;
            self.responseView.hidden = NO;
            [self.textView resignFirstResponder];
            break;
        default:
            break;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [self.textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
